package com.daxing.publishconfirm;

import com.daxing.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class SenderAsyncReturn {
    private static final String EXCHANGENAME = "routingexchange";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtils.getConnection();
        //声明通道,就类似于数据库的statment
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGENAME, "direct");
        channel.confirmSelect();//开启发布确认
        //异步接收发布确认结果,确认模式只负责到达交换机,有没有队列不关心
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("发送成功");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("fasong失败");
            }
        });

        //添加回退的监听器,当消息到达交换机但是没有队列接收的时候,会退回到生产者
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
            //当有消息被退回来的时候就会执行这个方法
                System.err.println("消息被退回来了:" + new String(body));
            }
        });

        //发送消息
        String msg = "感觉自己被骗了";

        for (int i = 0; i < 100; i++) {
            //mandatory 开启退回机制,不然addReturnListener不生效
            channel.basicPublish(EXCHANGENAME, "saoma",true, null, (msg + i).getBytes(StandardCharsets.UTF_8));
        }

//        //如果用不到就可以关闭了
        //channel.close();
      //  connection.close();
    }
}
